package club.kingyin.pathfilter.core;


import java.util.HashMap;
import java.util.Map;

public class PathFilter {

    private String[] paths;
    private Map<String,Boolean> cache = new HashMap<>();

    public PathFilter(String[] paths) {
        this.paths = paths;
    }

    public boolean intercept(String path) {
        Boolean res;
        if ((res = cache.get(path)) != null) {
            return res;
        }

        for (String s : paths) {
            if (choice(s,path)) {
                cache.put(path, true);
                return true;
            }
        }
        cache.put(path, false);
        return false;
    }

    /**
     *
     * @param target 目标
     * @param resource 原始路径
     * @return 匹配
     */
    public boolean choice(String target, String resource) {
        if (!target.contains("*") && !target.contains("**")) {
            return target.equals(resource);
        } else {
            String[] targets = target.split("/");
            String[] resources = resource.split("/");

            int ts = targets.length - 1;
            int rs = resources.length - 1;

            String currentT;
            String currentS;
            while (rs > 0 && ts > 0) {
                currentT = targets[ts];
                currentS = resources[rs];
                if (currentS.equals(currentT) || "*".equals(currentT)) {
                    ts--;
                    rs--;
                } else if ("**".equals(currentT)) {
                    if (targets[ts - 1].equals(currentS)) {
                        ts--;
                        continue;
                    }
                    rs--;
                } else {
                    return false;
                }
            }
            if (rs == 0 && ts == 0) {
                return true;
            }
            return false;
        }
    }
}
